package root.electronclass.electronclass.personal.activity

import android.content.res.ColorStateList
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import retrofit2.Call
import root.electronclass.electronclass.R
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.CommonDialogFragment
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.databinding.ActivityCharacterBinding
import root.electronclass.electronclass.databinding.ItemCharacter2Binding
import root.electronclass.electronclass.databinding.ItemCharacterBinding
import root.electronclass.electronclass.databinding.ItemPopupwindowBinding
import root.electronclass.electronclass.ext.doOnTabSelected
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.CompetitionScore
import root.electronclass.electronclass.mvp.entity.MoralScore
import root.electronclass.electronclass.mvp.entity.MoralScoreRecord
import root.electronclass.electronclass.mvp.entity.MoralTitle
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.personal.activity.model.CharacterModel
import root.electronclass.electronclass.personal.dialog.CharacterDetailDialog
import root.electronclass.electronclass.personal.dialog.PersonalGrowthDialog

class CharacterFragment : ViewBindingFragment<ActivityCharacterBinding>() {
    private val viewModel: CharacterModel by viewModels()
    private var dataType = 1
    private var competitionId: Long = 1
    private var popupWindow: PopupWindow? = null
    private var list = mutableListOf<MoralScore>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val onTabClick: (TabLayout.Tab) -> Unit = {
            dataType = it.tag as Int
            binding.popupWindow.isVisible = dataType == 4
            binding.ivMonthType.isVisible = dataType == 1
            binding.monthType.isVisible = dataType == 1
            viewModel.load(dataType, competitionId, 1)
            if (dataType == 1) {
                studentScoreList()
            } else {
                competitionScoreList()
            }
        }
        binding.tab.let {
            it.addTab(it.newTab().setText("校园德育").setTag(1))
            it.addTab(it.newTab().setText("竞赛德育").setTag(4))
            onTabClick.invoke(it.getTabAt(0)!!)
            it.doOnTabSelected { tab ->
                tab ?: return@doOnTabSelected
                onTabClick.invoke(tab)
            }
        }

        binding.recycler.adapter = adapter
        binding.fractionRecycler.adapter = adapter1

        viewModel.data.observe(viewLifecycleOwner) {
            if (it.first == 1) {
                if (!it.second.isNullOrEmpty()) {
                    if (dataType == 1) {
                        binding.ranking4.visibility = View.GONE
                        binding.textView21.text = "年级排名"
                        binding.monthType.text = it.second[0].dateInit
                    } else {
                        binding.ranking4.visibility = View.VISIBLE
                        binding.ranking4.text = it.second[0].score.toString()
                        binding.textView21.text = "竞赛排名"
                    }
                }
                adapter.refresh(it.second)
                if (it.second.isNotEmpty()) {
                    binding.recycler.smoothScrollToPosition(0)
                }
            } else {
                adapter.addAll(it.second)
            }
        }
        onClick()
        popupData()
        getMoralTitle()
        studentScoreList()
    }

    private fun onClick() {
        binding.popupWindow.setOnClickListener {
            popupWindow?.showAsDropDown(binding.popupWindow);
        }

        binding.growthSpace.setOnClickListener {
            PersonalGrowthDialog().show(childFragmentManager, "PersonalGrowthDialog")
        }
    }

    private val adapter = BasicAdapter<MoralScoreRecord, ItemCharacterBinding> { holder, item ->
        holder.binding.root.backgroundTintList = ColorStateList.valueOf(if (holder.adapterPosition % 2 == 0) 0 else 0xff7f8f9)
        holder.binding.name.text = item.ruleName
        holder.binding.detail.text = item.detail
        holder.binding.score.text = "${if (item.mark == 1) "+" else "-"}${item.score}"
        holder.binding.score.setTextColor(if (item.mark == 1) resources.getColor(R.color.c_093b5d) else resources.getColor(R.color.c_e85656))
        holder.binding.time.text = item.createTime
        holder.binding.created.text = item.creatorName
        holder.binding.subDetail.setOnClickListener {
            exmDetail(item.id!!)
        }
    }

    private val adapter1 = BasicAdapter<MoralTitle, ItemCharacter2Binding> { holder, item ->
        holder.binding.iv.setImageURI(item.picFormat?.get(0)?.url)
        holder.binding.tvNikeName.text = item.name
        holder.binding.time.text = "剩余有效期${item.surplusTime}天"
        holder.binding.type.text = when (item.validity) {
            1 -> "每日"
            2 -> "每周"
            3 -> "每月"
            4 -> "每学期"
            else -> {
                ""
            }
        }
        holder.binding.title.text = when (item.type) {
            1 -> "校园称号"
            2 -> "班级称号"
            3 -> "竞赛称号"
            4 -> "班级个人称号"
            else -> "荣誉称号"

        }
    }

    fun showPopWindow() { //自定义布局，作为PopupWindow显示的内容
        val activity = activity ?: return
        val contentView = LayoutInflater.from(activity).inflate(R.layout.pop_window, null);
        popupWindow = PopupWindow(contentView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true)

        val recyclerView = contentView.findViewById<RecyclerView>(R.id.recycler)
        val adapter = BasicAdapter<MoralScore, ItemPopupwindowBinding> { holder, item ->
            holder.binding.tv.text = item.name
            holder.binding.tv.setOnClickListener {
                competitionId = item.id
                binding.popupWindow.text = item.name
                popupWindow?.dismiss()
                competitionScoreList()
                viewModel.load(dataType, competitionId, 1)
            }
        }
        recyclerView.adapter = adapter
        adapter.notifyChanged(list)
        popupWindow?.isTouchable = true

        popupWindow?.setTouchInterceptor { p0, p1 -> false };
    }

    private fun exmDetail(id: Long) {
        RestManager.getInstance().initRest().examPageDetails(id).enqueue(object : CallbackNext<BaseResponse<MoralScoreRecord>>(mDialogViewModel) {
            override fun onSuccessful(call: Call<BaseResponse<MoralScoreRecord>>, response: BaseResponse<MoralScoreRecord>) {
                if (response.isSuccess && response.rows != null) {
                    CharacterDetailDialog().also {
                        it.arguments = bundleOf(
                            CommonDialogFragment.TITLE to "打分详情",
                            CharacterDetailDialog.DATA to response.rows,
                            CommonDialogFragment.CLOSE to true
                        )
                    }.show(childFragmentManager, "DFXQ")
                }
            }

            override fun onError(call: Call<BaseResponse<MoralScoreRecord>>?, response: BaseResponse<MoralScoreRecord>) {
                toast(response.msg)
            }

        })

    }

    private fun popupData() {
        RestManager.getInstance().initRest().moralScoreRecord(GlobalParameter.getSTUDENT().departId)
            .enqueue(object : CallbackNext<BaseResponse<List<MoralScore>>>(mDialogViewModel) {
                override fun onSuccessful(call: Call<BaseResponse<List<MoralScore>>>, response: BaseResponse<List<MoralScore>>) {
                    if (response.isSuccess && response.rows != null && response.rows.isNotEmpty()) {
                        binding.popupWindow.text = response.rows[0].name
                        competitionId = response.rows[0].id
                        list.addAll(response.rows)
                        showPopWindow()
                    }
                }

                override fun onError(call: Call<BaseResponse<List<MoralScore>>>?, response: BaseResponse<List<MoralScore>>) {
                    toast(response.msg)
                }

            })
    }


    private fun competitionScoreList() {
        binding.halfCircleChart.score = 0f
        binding.ranking1.isVisible = false
        binding.ranking2.isVisible = false
        binding.ranking3.isVisible = false
        binding.ranking4.isVisible = true
        binding.textView20.isVisible = false
        binding.textView22.isVisible = false
        val record = MoralScoreRecord()
        record.competitionId = competitionId
        record.studentId = GlobalParameter.getSTUDENT().userInfoVo.id
        RestManager.getInstance().initRest().competitionScoreList(record)
            .enqueue(object : CallbackNext<BaseResponse<CompetitionScore>>(mDialogViewModel) {
                override fun onSuccessful(call: Call<BaseResponse<CompetitionScore>>, response: BaseResponse<CompetitionScore>) {
                    if (response.isSuccess) {
                        binding.halfCircleChart.score = response.rows.score.toFloat()
                        binding.ranking4.text = response.rows.rank.toString()
                    }
                }

                override fun onError(call: Call<BaseResponse<CompetitionScore>>?, response: BaseResponse<CompetitionScore>) {
                    toast(response.msg)
                }

            })
    }

    private fun studentScoreList() {
        binding.halfCircleChart.score = 0f
        binding.ranking1.isVisible = true
        binding.ranking2.isVisible = true
        binding.ranking3.isVisible = true
        binding.textView20.isVisible = true
        binding.textView22.isVisible = true
        binding.ranking4.isVisible = false

        val record = MoralScoreRecord()
        record.competitionId = competitionId
        record.studentId = GlobalParameter.getSTUDENT().userInfoVo.id
        RestManager.getInstance().initRest().studentScoreList(record)
            .enqueue(object : CallbackNext<BaseResponse<MoralScoreRecord>>(mDialogViewModel) {
                override fun onSuccessful(call: Call<BaseResponse<MoralScoreRecord>>, response: BaseResponse<MoralScoreRecord>) {
                    if (response.isSuccess) {
                        binding.halfCircleChart.score = response.rows.studentScores.toFloat()
                        binding.ranking3.text = response.rows.listClass.toString()
                        binding.ranking2.text = response.rows.listGrade.toString()
                        binding.ranking1.text = response.rows.listSchool.toString()
                    }
                }

                override fun onError(call: Call<BaseResponse<MoralScoreRecord>>?, response: BaseResponse<MoralScoreRecord>) {
                    toast(response.msg)
                }

            })
    }

    private fun getMoralTitle() {

        RestManager.getInstance().initRest().getMoralTitle().enqueue(object : CallbackNext<BaseResponse<List<MoralTitle>>>(mDialogViewModel) {
            override fun onSuccessful(call: Call<BaseResponse<List<MoralTitle>>>, response: BaseResponse<List<MoralTitle>>) {
                if (response.isSuccess) {
                    adapter1.refresh(response.rows)
                }
            }

            override fun onError(call: Call<BaseResponse<List<MoralTitle>>>?, response: BaseResponse<List<MoralTitle>>) {
                toast(response.msg)
            }

        })
    }
}